var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var util = require('util');

var Link = new Schema({
	name : {
		type : String,
		unique : true
	},
	output : {
		type : Schema.ObjectId,
		ref : 'Port',
		unique : true
	},
	inputs : [ {
		type : Schema.ObjectId,
		ref : 'Port'
	} ],
	value : String,
	description : String,
	relation : String
});

Link.methods.calculate = function() {
	var self = this;
	var is = {};
	this.inputs.forEach(function(input) {
		is[input.sysId] = input.value;
	});

	function relation(inputs, relation) {
		log.debug(util.inspect(inputs));
		
		var output = null;
		log.debug("Relation: " + relation);
		eval(relation);
		
		return output;
	};
	
	this.value = relation(is, this.relation) || this.value;
	log.debug("New " + this.output.name + " Value: " + this.value);
	
	this.save(function(e) {
		log.debug("Emitting 'link_update'");
		tasks.emit('link_update', self.output._id || self.output, self.value);
	});
};

//model.Link = mongoose.model('Link', Link);

tasks.on('port_update', function(id, value) {
	model.Link.find({
		inputs : id
	}).populate('inputs').populate('output').run(function(e, links) {
		links.forEach(function(link) {
			log.debug("Recalculating Link " + link._id);
			link.calculate();
		});
	});
});
